package com.globant.google.mendoza;

import java.util.Properties;

import com.globant.google.mendoza.malbec.transport.Receiver;
import com.globant.google.mendoza.malbec.transport.StandAlone;

public final class GoogleCheckoutMock {

  private StandAlone transport;

  public GoogleCheckoutMock() {
    initTransport();
  }

  private void sendNotifications() {
    System.out.println("GoogleCheckoutMock.sendNotifications() - start");
    transport.send(getNewOrderNotification());
    transport.send(getOrderStateChangeNotification());
    transport.send(getRiskInformationNotification());
    System.out.println("GoogleCheckoutMock.sendNotifications() - end");
  }

  private void initTransport() {
    transport = new StandAlone(null, null,
        MendozaTestConstants.merchantId, MendozaTestConstants.merchantKey,
        MendozaTestConstants.callbackURL,
        MendozaTestConstants.googleCheckoutMockPort, true);
    transport.registerReceiver(new GoogleCheckoutMockReceiver());
    transport.start();
    System.out.println("google checkout mock started...");
  }

  private String getRiskInformationNotification() {
    return MendozaTestConstants.riskInformationNOtification;
  }

  private String getOrderStateChangeNotification() {
    return MendozaTestConstants.orderStateChangeNotification;
  }

  private String getNewOrderNotification() {
    return MendozaTestConstants.newOrderNotification;
  }

  private class GoogleCheckoutMockReceiver implements Receiver {

   public String receive(final String uri, final String method,
       final Properties header, final Properties params, final String message) {
     System.out.println("GoogleCheckoutMockReceiver.receive() - start");
     System.out.println("message received: " + message);
     String result = "Cannot understand request";
     if (message.contains("checkout-shopping-cart")) {
       result = "OK";
     }
     System.out.println("GoogleCheckoutMockReceiver.receive() - end");
     return result;
   }

    public void received(final String message) {
      sendNotifications();
    }
  }
}
